package com.luomu.base.biz.cookBook.redisLock.constant;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

//import javax.annotation.PostConstruct;

/**
 *  redis 锁机制
 *  是“死等锁”，直到拿到为止；
*/
@Component
public class RedisLock {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisLock.class);

    private static final int lockSeconds = 5;
    private static final int lockSecondsBig = 10;

    @Resource
    private RedissonClient redissonClient;
    private static RedissonClient redisson = null;

    @PostConstruct
    public void init(){
        if(redisson != null){
            return;
        }
        redisson = redissonClient;
    }


    public static RLock acquire(String lockName){
//        init();
        LOGGER.info("======info lock======"+ lockName);
        RLock lock = redisson.getLock(lockName);
        lock.lock(lockSeconds, TimeUnit.SECONDS); //lock提供带timeout参数，timeout结束强制解锁，防止死锁
        LOGGER.info("======get lock======"+ lockName);
        return lock;
    }

    public static RLock acquireBigTime(String lockName){
        LOGGER.info("======info lock======"+ lockName);
        RLock lock = redisson.getLock(lockName);
        lock.lock(lockSecondsBig, TimeUnit.SECONDS); //lock提供带timeout参数，timeout结束强制解锁，防止死锁
        LOGGER.info("======get lock======"+ lockName);
        return lock;
    }

    public static void release(RLock lock){
        LOGGER.info("======unlock======"+ lock.getName());
        try {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void release(String lockName){
        LOGGER.info("======unlock======"+ lockName);
        RLock lock = redisson.getLock(lockName);
        if(lock != null && lock.isHeldByCurrentThread()){
            try {
                redisson.getLock(lockName).unlock();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
